<template>
  <div id="newMessage" v-if="val != '/login' && status == true">
    <div v-for="(item, index) in data" :key="index" class="newMessage">
      <div>
        <div class="newtitle">
          <h1>
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-xiaoxi"></use>
            </svg>
            你有一条新消息
          </h1>
          <i class="el-icon-close" @click="close(item)"></i>
        </div>
        <div class="context">
          <p>
            {{ item.title }}
          </p>
        </div>
        <div class="caozuo">
          <el-button type="primary" round @click="accept(item)">接受</el-button>
          <el-button type="warning" round @click="refuse(item)">拒绝</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import { mapActions } from 'vuex';

  export default {
    name: 'newMessage',
    data() {
      return {
        websocket: null,
        lockReconnect: false,
        everyStatus: false,
        byStatus: false,
        timer: null,
        val: '',
        oldval: '',
        status: false,
        arr: [], //存放在vuex中
        data: [] //页面使用
      };
    },
    filters: {
      ellipsis(value) {
        if (!value) return '';
        if (value.length > 15) {
          return value.slice(0, 15) + '...';
        }
        return value;
      }
    },
    mounted() {
      this.initWebSocket();
      // 自动消失
    },
    methods: {
      ...mapActions(['commitMessageDate', 'delMessageDate']),

      initWebSocket() {
        //初始化weosocket
        let userId = 1;
        if (window.location.hash !== '#/login' && this.$store.state.userInfo.token !== '') {
          const wsuri = 'ws://118.123.236.2:8080/WebSocketServer?userId=' + userId; //连接地址，可加参数
          this.websocket = new WebSocket(wsuri);
          this.websocket.onopen = this.websocketonopen;
          this.websocket.onerror = this.websocketonerror;
          this.websocket.onmessage = this.websocketonmessage;
          this.websocket.onclose = this.websocketclose;
        } else {
          return;
        }
      },
      //WebSocket连接成功
      websocketonopen(e) {
        console.log(e);
        //heartCheck.reset().start() //心跳检测
      },
      //WebSocket连接错误
      websocketonerror() {
        //重连
        this.reconnect();
      },
      //WebSocket接受消息
      websocketonmessage(e) {
        this.status = true;
        this.arr.push({
          title: JSON.parse(e.data).websocketMessage,
          path: e.path
        });
        this.data.push({
          title: JSON.parse(e.data).websocketMessage,
          path: e.path
        });
        this.commitMessageDate(this.arr);
      },
      //WebSocket发送消息
      websocketsend(agentData) {
        //数据发送
        this.websock.send(agentData);
      },
      //WebSocket关闭
      websocketclose(e) {
        console.log('connection closed (' + e.code + ')');
      },
      //重连
      reconnect() {
        var that = this;
        if (that.lockReconnect) return;
        that.lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        setTimeout(function () {
          console.info('尝试重连...');
          that.initWebSocket();
          that.lockReconnect = false;
        }, 5000);
      },
      //关闭弹窗并在vuex中删除
      close(item) {
        this.guan(item);
        this.delMessageDate(item);
      },
      //关闭
      guan(item) {
        for (let i = 0; i < this.data.length; i++) {
          if (this.data[i] === item) {
            this.data.splice(i, 1);
            i--;
          }
        }
        return this.arr;
      },
      //接受任务
      accept(item) {
        this.delMessageDate(item);
        this.guan(item);
      },
      //拒绝任务
      refuse(item) {
        this.close(item);
      }
    },
    watch: {
      //监听路由在登录页面不挂载此消息通知组件
      $route: {
        handler(val, oldval) {
          this.val = val.path; //新路由信息
          this.oldval = oldval.path; //老路由信息
          if (val.path !== '/login') {
            this.initWebSocket();
          } else {
            this.websocketclose();
          }
        },
        // 深度观察监听
        deep: true
      },
      //监听消息数组
      data() {
        console.log(this.data, this.arr);
        let that = this;
        if (that.data.length === 0) {
          return;
        }
        //背景颜色
        setTimeout(function () {
          let pic = document.getElementById('newMessage').children;
          // console.log(pic);
          if (pic.length < 5) {
            for (let i = 0; i < pic.length; i++) {
              pic[i].style.backgroundColor = '#ffffff';
              pic[i].style.opacity = '1';
              pic[i].style.borderRadius = '10px';
            }
            return;
          }
          for (let i = 0; i < pic.length; i++) {
            if (i < pic.length - 5) {
              pic[i].style.backgroundColor = '#ffffff';
              pic[i].style.opacity = '0.5';
            } else {
              pic[i].style.backgroundColor = '#ffffff';
              pic[i].style.opacity = '1';
            }
            pic[i].style.borderRadius = '10px';
          }
        }, 0);
        //自动消失
        if (that.everyStatus) return;
        that.everyStatus = true;
        setTimeout(function () {
          that.data.shift();
          that.everyStatus = false;
        }, 50000);
      }
    }
  };
</script>
<style lang="scss" scoped>
  #newMessage {
    position: fixed;
    bottom: 15px;
    right: 25px;
    width: 280px;
    z-index: 1;
    overflow: hidden;
    .icon {
      width: 1em;
      height: 1em;
      vertical-align: -0.15em;
      fill: currentColor;
      overflow: hidden;
    }
    .caozuo {
      text-align: center;
      button {
        width: 100px;
        height: 30px;
        text-align: center;
        padding: 0;
      }
    }
  }
  .newMessage {
    > div {
      margin-bottom: 10px;
      box-shadow: 0px 10px 20px rgba(28, 108, 191, 0.1);
      opacity: 1;
      border-radius: 10px;
      padding: 15px 26px 15px 20px;
      box-sizing: border-box;
      z-index: 2;
    }
    .el-icon-close {
      display: inline-block;
    }
    .newtitle {
      display: flex;
      justify-content: space-between;
      > h1 {
        font-size: 16px;
        line-height: 22px;
        height: 22px;
        font-weight: bold;
        margin-bottom: 5px;
      }
    }
    .context {
      font-size: 13px;
      font-weight: 500;
      line-height: 20px;
      color: #79838f;
      opacity: 1;
      margin-bottom: 10px;
    }
  }
</style>
